package com.mysql.study.test.dataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.beans.ConstructorProperties;
import java.util.HashMap;
import java.util.Map;

@Component
@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.a-master")
    public DataSource aMasterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.b-master")
    public DataSource bMasterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(@Qualifier("aMasterDataSource") DataSource aMasterDataSource, @Qualifier("bMasterDataSource") DataSource bMasterDataSource) {
        Map<Object,Object> map = new HashMap<>();
        map.put("a-master",aMasterDataSource);
        map.put("b-master",bMasterDataSource);
        return new DynamicDataSource(aMasterDataSource,map);

    }
}
